package com.shux.common.Interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.shux.common.exception.ShuxRunTimeException;
import com.shux.utils.constants.Constant;

/**
 **********************************************
 *  描述：异常统一处理
 * Simba.Hua
 * 2017年6月17日
 **********************************************
**/
public class ShuxExceptionJsonHandler implements HandlerExceptionResolver{
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        ShuxRunTimeException se = null;
        logger.error(ex.getMessage(),ex);
        if(ex instanceof ShuxRunTimeException){
            se = (ShuxRunTimeException)ex;
        } else if(ex instanceof IncorrectCredentialsException || ex instanceof UnknownAccountException){
            se = new ShuxRunTimeException(Constant.EXCEPTION_MESSAGE_USERNAME_PASSWORD_ISNOT_CORRECT);
        } else if(ex instanceof UnauthorizedException){
            se = new ShuxRunTimeException(Constant.EXCEPTION_MESSAGE_YOU_ARE_FORBIDDEN);
        }else{
            se = new ShuxRunTimeException(Constant.EXCEPTION_OTHER_ERROR);
        }
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        String msg = getMessage(se.getMessage());
        
        try {
            PrintWriter writer = response.getWriter();
            writer.write(msg);
            writer.flush();
        } catch (IOException e) {
            logger.error("写入jsp失败",e);
        }
        logger.info(msg);
        
        ModelAndView mv = new ModelAndView();
        return mv;
    }
    
    private String getMessage(String message){
        StringBuffer result = new StringBuffer();
        result.append("{\"success\":false,\"msg\":\"")
              .append(message)
              .append("\"")
              .append("}");
        return result.toString();
    }

}
